#include "dialogmain.h"
#include "ui_dialogmain.h"
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QMenu>
#include <QMessageBox>
#include <QSettings>
#include <QTimer>
#include "serialsettingsdialog.h"

DialogMain::DialogMain(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogMain)
{
    ui->setupUi(this);

    loadConfig(QCoreApplication::applicationDirPath() + "/" + DEF_INI_FILENAME);

    initContextMenu();
    initWidget();
    initSerialPort();

    connect(this, SIGNAL(signalMinuteChange(const QDateTime &)), this, SLOT(onMinuteChanged(const QDateTime &)));
    connect(this, SIGNAL(signalDayChange(const QDateTime &)), this, SLOT(onDayChanged(const QDateTime &)));
    mOneSecondTimerId = startTimer(1000);

    qDebug() << QCoreApplication::applicationFilePath();
    qDebug() << QCoreApplication::applicationDirPath();
}

DialogMain::~DialogMain()
{
    if (mOneSecondTimerId) {
        killTimer(mOneSecondTimerId);
        mOneSecondTimerId = 0;
    }

    savePowerLog((unsigned int)-1, (unsigned int)-1, (unsigned int)-1, (unsigned int)-1, (unsigned int)-1, (unsigned int)-1);

    saveConfig(QCoreApplication::applicationDirPath() + "/" + DEF_INI_FILENAME);

    delete ui;
}

void DialogMain::timerEvent(QTimerEvent *e)
{
    if (e->timerId() == mOneSecondTimerId) {
        QDateTime curDateTime = QDateTime::currentDateTime();

        if (2014 <= curDateTime.date().year()) {
            static int _oldMinute = -1, _oldDay = -1;

            if (0 == curDateTime.time().second()) {
                if (curDateTime.time().minute() != _oldMinute) {
                    _oldMinute = curDateTime.time().minute();
                    emit signalMinuteChange(curDateTime);
                }
            } else if (30 == curDateTime.time().second()) {
                if (curDateTime.date().day() != _oldDay) {
                    _oldDay = curDateTime.date().day();
                    emit signalDayChange(curDateTime);
                }
            }
        }
    }
}

void DialogMain::loadConfig(const QString fileName)
{
    QSettings settings(fileName, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    settings.beginGroup("MiscInfo");
    mMiscInfo.mLogIntervalMinute = settings.value("logIntervalMinute", 15).toInt();
    settings.endGroup();

    settings.beginGroup("SerialPort");
#ifdef Q_OS_WIN32
    mSerialPort.mName = settings.value("name", "COM3").toString();
#else
    mSerialPort.mName = settings.value("name", "ttyO4").toString();
#endif
    mSerialPort.mPortSettings.BaudRate = (BaudRateType)settings.value("baudRate", 9600).toInt();
    mSerialPort.mPortSettings.DataBits = (DataBitsType)settings.value("dataBits", 8).toInt();
    mSerialPort.mPortSettings.Parity = (ParityType)settings.value("parity", 0).toInt();
    mSerialPort.mPortSettings.StopBits = (StopBitsType)settings.value("stopBits", STOP_1).toInt();
    mSerialPort.mPortSettings.FlowControl = (FlowType)settings.value("flowControl", 0).toInt();
    mSerialPort.mPortSettings.Timeout_Millisec = settings.value("timeout", 10).toInt();
    settings.endGroup();
}

void DialogMain::saveConfig(const QString fileName)
{
    QFile::remove(fileName);
    QSettings settings(fileName, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    settings.beginGroup("MiscInfo");
    settings.setValue("logIntervalMinute", mMiscInfo.mLogIntervalMinute);
    settings.endGroup();

    settings.beginGroup("SerialPort");
    settings.setValue("name", mSerialPort.mName);
    settings.setValue("baudRate", mSerialPort.mPortSettings.BaudRate);
    settings.setValue("dataBits", mSerialPort.mPortSettings.DataBits);
    settings.setValue("parity", mSerialPort.mPortSettings.Parity);
    settings.setValue("stopBits", mSerialPort.mPortSettings.StopBits);
    settings.setValue("flowControl", mSerialPort.mPortSettings.FlowControl);
    settings.setValue("timeout", (int)mSerialPort.mPortSettings.Timeout_Millisec);
    settings.endGroup();
}

void DialogMain::initContextMenu()
{
    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(onShowContextMenu(const QPoint&)));
}

void DialogMain::initWidget()
{
}

void DialogMain::initSerialPort()
{
    mpSerialPort = new QextSerialPort(mSerialPort.mName);
    connect(mpSerialPort, SIGNAL(readyRead()), SLOT(onSerialPortRead()));

    mpSerialEnumerator = new QextSerialEnumerator(this);
    mpSerialEnumerator->setUpNotifications();
    connect(mpSerialEnumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onSerialPortAdded(QextPortInfo)));
    connect(mpSerialEnumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onSerialPortRemoved(QextPortInfo)));

    QTimer::singleShot(1, this, SLOT(onSerialPortOpen()));
}


unsigned short DialogMain::modbusCrc(unsigned char *data, int length)
{
    static const unsigned short tableCRC[] = {
        0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
        0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
        0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
        0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
        0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
        0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
        0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
        0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
        0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
        0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
        0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
        0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
        0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
        0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
        0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
        0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
        0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
        0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
        0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
        0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
        0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
        0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
        0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
        0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
        0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
        0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
        0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
        0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
        0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
        0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
        0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
        0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
    };

    unsigned char idxCRC;
    unsigned short wordCRC = 0xFFFF;

    while (length--) {
        idxCRC = *data++ ^ wordCRC;
        wordCRC >>= 8;
        wordCRC ^= tableCRC[idxCRC];
    }

    return wordCRC;
}

void DialogMain::modbusSetTime(QByteArray &ba)
{
    QDateTime curDateTime = QDateTime::currentDateTime();

    if (2014 <= curDateTime.date().year()) {
        unsigned short data, lock = 0x1234;

        ba.push_back(0x01); // device
        ba.push_back(0x10); // function : 16(Write Multiple Registers)

        data = 0;   // 40000 + 0
        ba.push_back((data>>8) & 0xFF); // msb_address
        ba.push_back((data>>0) & 0xFF); // lsb_address

        data = 8;   // lock(2), year(2), month(2), day(2), weekdays(2), hour(2), minute(2), second(2)
        ba.push_back((data>>8) & 0xFF); // msb_quantities
        ba.push_back((data>>0) & 0xFF); // lsb_quantities

        ba.push_back(0x10); // byte count : n * 2

        ba.push_back((lock>>8) & 0xFF); // msb_lock
        ba.push_back((lock>>0) & 0xFF); // lsb_lock

        data = curDateTime.date().year();
        ba.push_back((data>>8) & 0xFF); // msb_year
        ba.push_back((data>>0) & 0xFF); // lsb_year

        data = curDateTime.date().month();
        ba.push_back((data>>8) & 0xFF); // msb_month
        ba.push_back((data>>0) & 0xFF); // lsb_month

        data = curDateTime.date().day();
        ba.push_back((data>>8) & 0xFF); // msb_day
        ba.push_back((data>>0) & 0xFF); // lsb_day

        data = curDateTime.date().dayOfWeek() % 7;
        ba.push_back((data>>8) & 0xFF); // msb_weekdays
        ba.push_back((data>>0) & 0xFF); // lsb_weekdays

        data = curDateTime.time().hour();
        ba.push_back((data>>8) & 0xFF); // msb_hour
        ba.push_back((data>>0) & 0xFF); // lsb_hour

        data = curDateTime.time().minute();
        ba.push_back((data>>8) & 0xFF); // msb_minute
        ba.push_back((data>>0) & 0xFF); // lsb_minute

        data = curDateTime.time().second();
        ba.push_back((data>>8) & 0xFF); // msb_second
        ba.push_back((data>>0) & 0xFF); // lsb_second

        data = modbusCrc((unsigned char *)ba.data(), ba.length());
        ba.push_back((data>>0) & 0xFF);  // lsb_crc
        ba.push_back((data>>8) & 0xFF);  // msb_crc

        qDebug() << ba.toHex();
    }
}

void DialogMain::modbusGetTime(QByteArray &ba)
{
    unsigned short data;

    ba.push_back(0x01); // device
    ba.push_back(0x03); // function : 3(Read Holding Registers)

    data = 1;   // 40000 + 1
    ba.push_back((data>>8) & 0xFF); // msb_address
    ba.push_back((data>>0) & 0xFF); // lsb_address

    data = 7;   // year(2), month(2), day(2), weekdays(2), hour(2), minute(2), second(2)
    ba.push_back((data>>8) & 0xFF); // msb_quantities
    ba.push_back((data>>0) & 0xFF); // lsb_quantities

    data = modbusCrc((unsigned char *)ba.data(), ba.length());
    ba.push_back((data>>0) & 0xFF);  // lsb_crc
    ba.push_back((data>>8) & 0xFF);  // msb_crc
}

void DialogMain::modbusGetSum(QByteArray &ba)
{
    unsigned short data;

    ba.push_back(0x01); // device
    ba.push_back(0x04); // function : 4(Read Input Register)

    data = 8000;   // 30000 + 8000
    ba.push_back((data>>8) & 0xFF); // msb_address
    ba.push_back((data>>0) & 0xFF); // lsb_address

    data = 24;   // sum(4), this month(4), last month(4)
    ba.push_back((data>>8) & 0xFF); // msb_quantities
    ba.push_back((data>>0) & 0xFF); // lsb_quantities

    data = modbusCrc((unsigned char *)ba.data(), ba.length());
    ba.push_back((data>>0) & 0xFF);  // lsb_crc
    ba.push_back((data>>8) & 0xFF);  // msb_crc
}

void DialogMain::savePowerLog(unsigned int sum1, unsigned int this_month1, unsigned int last_month1,
                              unsigned int sum2, unsigned int this_month2, unsigned int last_month2)
{
    QDateTime curDateTime = QDateTime::currentDateTime();

    QString msg = curDateTime.toString("[yyyy-MM-dd hh:mm:ss]") + QString("\t%1\t%2\t%3\t%4\t%5\t%6").arg(sum1).arg(this_month1).arg(last_month1).arg(sum2).arg(this_month2).arg(last_month2);
#ifdef  Q_OS_WIN
    QString fileName = QString("%1/power_%2.log").arg(QCoreApplication::applicationDirPath()).arg(curDateTime.toString("yyyy-MM-dd"));
#else
    QString fileName = QString("%1/power_%2.log").arg(QDir::homePath()).arg(curDateTime.toString("yyyy-MM-dd"));
#endif

    QFile logFile(fileName);
    if (logFile.open(QFile::WriteOnly | QFile::Append | QFile::Text)) {
        QTextStream out(&logFile);
        out << msg << "\n";
        logFile.close();
    }
}


void DialogMain::onParseArgs(const QString& args)
{
    qDebug() << args;
    if (0 == args.compare("quit")) {
        qApp->quit();
    } else {
        emit signalNeedToShow();
    }
}

/*void DialogMain::onLog(const QString log)
{
    if (mMiscInfo.mIsLog) {
        QDateTime curDateTime = QDateTime::currentDateTime();
        QString msg = curDateTime.toString("[yyyy-MM-dd hh:mm:ss:zzz]") + log;
        const int MAX_FILE_SIZE = 1<<20; // 1[MB]

        int fileNum = 0;
        do {
            QString fileName = QString("%1-%2.log").arg(QCoreApplication::applicationFilePath()).arg(fileNum);
            QFile logFile(fileName);
            if (logFile.open(QFile::WriteOnly | QFile::Append | QFile::Text)) {
                if (MAX_FILE_SIZE < logFile.size()) {
                    fileNum++;
                } else {
                    QTextStream out(&logFile);
                    out << msg << "\n";
                    fileNum = 0;
                }
                logFile.close();
            } else {
                fileNum = 0;
            }
        } while (fileNum);
    }
}*/

void DialogMain::onShowContextMenu(const QPoint& pos)
{
    Q_UNUSED(pos);

    QMenu* contextMenu = new QMenu(this);
    contextMenu->addAction("SerialPort", this, SLOT(onMenuSerialPort()));
    contextMenu->addSeparator();
    if (mpSerialPort->isOpen()) {
        contextMenu->addAction("ModbusSetTime", this, SLOT(onMenuSetTime()));
        contextMenu->addAction("ModbusGetTime", this, SLOT(onMenuGetTime()));
        contextMenu->addAction("ModbusGetSum", this, SLOT(onMenuGetSum()));
        contextMenu->addSeparator();
    }
    contextMenu->addAction("Exit", this, SLOT(onMenuExit()));
    contextMenu->exec(mapToGlobal(pos));
    delete contextMenu;
}

void DialogMain::onMenuSerialPort()
{
    SerialSettingsDialog dlg(mSerialPort.mName, &mSerialPort.mPortSettings, this);
    if (QDialog::Accepted == dlg.exec()) {
        mSerialPort.mName = dlg.name();

        saveConfig(QCoreApplication::applicationDirPath() + "/" + DEF_INI_FILENAME);

        QTimer::singleShot(1, this, SLOT(onSerialPortOpen()));
    }
}

void DialogMain::onMenuSetTime()
{
    QByteArray ba;
    modbusSetTime(ba);
    qDebug() << "onMenuSetTime : " << ba.toHex();
    mpSerialPort->write(ba);
}

void DialogMain::onMenuGetTime()
{
    QByteArray ba;
    modbusGetTime(ba);
    qDebug() << "onMenuGetTime : " << ba.toHex();
    mpSerialPort->write(ba);
}

void DialogMain::onMenuGetSum()
{
    QByteArray ba;
    modbusGetSum(ba);
    qDebug() << "onMenuGetSum : " << ba.toHex();
    mpSerialPort->write(ba);
}

void DialogMain::onMenuExit()
{
    qApp->quit();
}

void DialogMain::onDayChanged(const QDateTime &dt)
{
    Q_UNUSED(dt);
    onMenuSetTime();
}

void DialogMain::onMinuteChanged(const QDateTime &dt)
{
    qDebug() << "onMinuteChanged()";
    if (0 == (dt.time().minute() % mMiscInfo.mLogIntervalMinute)) {
        onMenuGetSum();
    }
}


void DialogMain::onSerialPortOpen()
{
    onSerialPortClose();

    mpSerialPort->setPortName(mSerialPort.mName);
    mpSerialPort->setQueryMode(QextSerialPort::EventDriven);
    mpSerialPort->setBaudRate(mSerialPort.mPortSettings.BaudRate);
    mpSerialPort->setDataBits(mSerialPort.mPortSettings.DataBits);
    mpSerialPort->setParity(mSerialPort.mPortSettings.Parity);
    mpSerialPort->setStopBits(mSerialPort.mPortSettings.StopBits);
    mpSerialPort->setFlowControl(mSerialPort.mPortSettings.FlowControl);
    mpSerialPort->setTimeout(mSerialPort.mPortSettings.Timeout_Millisec);

    if (mpSerialPort->open(QIODevice::ReadWrite)) {
        qDebug() << "+ SerialPort Open : " << mSerialPort.mName;
        QTimer::singleShot(100, this, SLOT(onSerialPortSend()));
    } else {
        qDebug() << "!!! SerialPort Open Error !!!";
        QMessageBox msgBox;
        msgBox.setText("!!! SerialPort Open Error !!!");
        msgBox.exec();
    }
}

void DialogMain::onSerialPortClose()
{
    mSerialPortRecvBuf.clear();
    if (mpSerialPort->isOpen()) {
        mpSerialPort->close();
        qDebug() << "- SerialPort Open : " << mSerialPort.mName;
    }
}

void DialogMain::onSerialPortSend()
{
    onMenuSetTime();
}

void DialogMain::onSerialPortRead()
{
    if (mpSerialPort->bytesAvailable()) {
        mSerialPortRecvBuf += mpSerialPort->readAll();

        while (PACKET_MIN_LEN <= mSerialPortRecvBuf.count()) {
            while (PACKET_SLAVE_ADDR != mSerialPortRecvBuf.at(0)) {
                mSerialPortRecvBuf.remove(0, 1);
                if (PACKET_MIN_LEN > mSerialPortRecvBuf.count()) {
                    return;
                }
            }

            int nFunctionCode = mSerialPortRecvBuf.at(1), nLength;
            if (16 == nFunctionCode) {
                // slave_address(1) + function_code(1) + data_address(2) + num_register(2) + crc(2)
                nLength = 8;
                if (mSerialPortRecvBuf.count() < nLength) {
                    return;
                }

                unsigned char lsb, msb;
                unsigned short dataAddress, numRegisters, crcRecv;

                lsb = (unsigned char)mSerialPortRecvBuf.at(2);
                msb = (unsigned char)mSerialPortRecvBuf.at(3);
                dataAddress = ((unsigned short)lsb<<8) + msb;
                lsb = (unsigned char)mSerialPortRecvBuf.at(4);
                msb = (unsigned char)mSerialPortRecvBuf.at(5);
                numRegisters = ((unsigned short)lsb<<8) + msb;

                lsb = (unsigned char)mSerialPortRecvBuf.at(6);
                msb = (unsigned char)mSerialPortRecvBuf.at(7);
                crcRecv = ((unsigned short)msb<<8) + lsb;

                qDebug() << "modbusSetTime : " << dataAddress << numRegisters << crcRecv;
            } else {
                nLength = mSerialPortRecvBuf.at(2) + PACKET_MIN_LEN;
                if (mSerialPortRecvBuf.count() < nLength) {
                    return;
                }

                unsigned char lsb = (unsigned char)mSerialPortRecvBuf.at(nLength - 2);
                unsigned char msb = (unsigned char)mSerialPortRecvBuf.at(nLength - 1);
                unsigned short crcRecv = ((unsigned short)msb<<8) + lsb;
                if (modbusCrc((unsigned char *)mSerialPortRecvBuf.data(), (nLength - 2)) == crcRecv) {
                    qDebug() << "onSerialPortRead : " << mSerialPortRecvBuf.toHex();

                    switch (nFunctionCode) {
                    case 0x03:  // modbusGetTime()
                    {
                        unsigned short year, month, day, weekdays, hour, minute, second;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(3);
                        msb = (unsigned char)mSerialPortRecvBuf.at(4);
                        year = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(5);
                        msb = (unsigned char)mSerialPortRecvBuf.at(6);
                        month = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(7);
                        msb = (unsigned char)mSerialPortRecvBuf.at(8);
                        day = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(9);
                        msb = (unsigned char)mSerialPortRecvBuf.at(10);
                        weekdays = ((unsigned short)lsb<<8) + msb;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(11);
                        msb = (unsigned char)mSerialPortRecvBuf.at(12);
                        hour = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(13);
                        msb = (unsigned char)mSerialPortRecvBuf.at(14);
                        minute = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(15);
                        msb = (unsigned char)mSerialPortRecvBuf.at(16);
                        second = ((unsigned short)lsb<<8) + msb;

                        qDebug() << "modbusGetTime : " << year << month << day << weekdays << hour << minute << second;
                    }
                        break;
                    case 0x04:  // modbusGetSum()
                    {
                        unsigned short lsbShort, msbShort;
                        unsigned int sum1, this_month1, last_month1;
                        unsigned int sum2, this_month2, last_month2;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(3);
                        msb = (unsigned char)mSerialPortRecvBuf.at(4);
                        lsbShort = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(5);
                        msb = (unsigned char)mSerialPortRecvBuf.at(6);
                        msbShort = ((unsigned short)lsb<<8) + msb;
                        sum1 = ((unsigned int)lsbShort<<16) + msbShort;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(7);
                        msb = (unsigned char)mSerialPortRecvBuf.at(8);
                        lsbShort = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(9);
                        msb = (unsigned char)mSerialPortRecvBuf.at(10);
                        msbShort = ((unsigned short)lsb<<8) + msb;
                        this_month1 = ((unsigned int)lsbShort<<16) + msbShort;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(11);
                        msb = (unsigned char)mSerialPortRecvBuf.at(12);
                        lsbShort = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(13);
                        msb = (unsigned char)mSerialPortRecvBuf.at(14);
                        msbShort = ((unsigned short)lsb<<8) + msb;
                        last_month1 = ((unsigned int)lsbShort<<16) + msbShort;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(39);
                        msb = (unsigned char)mSerialPortRecvBuf.at(40);
                        lsbShort = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(41);
                        msb = (unsigned char)mSerialPortRecvBuf.at(42);
                        msbShort = ((unsigned short)lsb<<8) + msb;
                        sum2 = ((unsigned int)lsbShort<<16) + msbShort;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(43);
                        msb = (unsigned char)mSerialPortRecvBuf.at(44);
                        lsbShort = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(45);
                        msb = (unsigned char)mSerialPortRecvBuf.at(46);
                        msbShort = ((unsigned short)lsb<<8) + msb;
                        this_month2 = ((unsigned int)lsbShort<<16) + msbShort;

                        lsb = (unsigned char)mSerialPortRecvBuf.at(47);
                        msb = (unsigned char)mSerialPortRecvBuf.at(48);
                        lsbShort = ((unsigned short)lsb<<8) + msb;
                        lsb = (unsigned char)mSerialPortRecvBuf.at(49);
                        msb = (unsigned char)mSerialPortRecvBuf.at(50);
                        msbShort = ((unsigned short)lsb<<8) + msb;
                        last_month2 = ((unsigned int)lsbShort<<16) + msbShort;

                        savePowerLog(sum1, this_month1, last_month1, sum2, this_month2, last_month2);
                        qDebug() << "modbusGetSum : " << sum1 << this_month1 << last_month1 << sum2 << this_month2 << last_month2;
                    }
                        break;
                    default:
                        break;
                    }
                }
            }

            mSerialPortRecvBuf.remove(0, nLength);
        }
    }
}

void DialogMain::onSerialPortAdded(QextPortInfo portInfo)
{
    qDebug() << "onSerialPortAdded : " << portInfo.portName;
    if (0 == portInfo.portName.compare(mSerialPort.mName)) {
        // open
    }
}

void DialogMain::onSerialPortRemoved(QextPortInfo portInfo)
{
    qDebug() << "onSerialPortRemoved : " << portInfo.portName;
    if (0 == portInfo.portName.compare(mSerialPort.mName)) {
        // close
    }
}
